<template>

    <h1 style="margin-top: 30px;">养殖信息 <el-button type="primary" style="margin-left: 20px;"
            @click="CuitvaCreate">设置</el-button></h1>
    <hr>
    <div style="margin-top: 30px;">
        <span>品种: {{ data?.sourceName }}</span><span style="margin-left: 200px;">来源:{{ data?.source }} </span>
    </div>
    <div style="margin-top: 20px;">
        <span>饲养天数:{{ data?.sourceDay }} </span><span style="margin-left: 160px;">饲养品牌: {{ data?.sourceBrand }}</span>
    </div>
    <div style="margin-top: 20px;">
        <span>饲养负责人:{{ data?.sourceUser }} </span><span style="margin-left: 150px;">出栏日期:{{ data?.slantTime }} </span>
    </div>


    <el-dialog v-model="dialogFormVisible" title="新增养殖信息" width="500">
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">
            <el-form-item label="品种" prop="sourceName">
                <el-input v-model="ruleForm.sourceName" />
            </el-form-item>
            <el-form-item label="来源" prop="source">
                <el-input v-model="ruleForm.source" />
            </el-form-item>
            <el-form-item label="饲养天数" prop="sourceDay">
                <el-input v-model="ruleForm.sourceDay" />
            </el-form-item>
            <el-form-item label="饲养品牌" prop="sourceBrand">
                <el-input v-model="ruleForm.sourceBrand" />
            </el-form-item>
            <el-form-item label="饲养负责人" prop="sourceUser">
                <el-input v-model="ruleForm.sourceUser" />
            </el-form-item>
            <el-form-item label="出栏日期" prop="slantTime">
                <el-date-picker v-model="ruleForm.slantTime" type="date" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    新增
                </el-button>
                <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
    <h1 style="margin-top: 40px;">保健信息 <el-button type="primary" style="margin-left: 20px;"
            @click="AddRow">新增行</el-button></h1>
    <hr>
    <el-table :data="model.tableData" style="width: 100%">
        <el-table-column prop="date" label="饲养天数" width="180">
            <template v-slot="scoped">
                <template v-if="scoped.row.isEditing">
                    <el-input style="width: 120px;" v-model="scoped.row.scountNum" />
                </template>
                <template v-else>
                    {{ scoped.row.scountNum }}
                </template>
            </template>
        </el-table-column>
        <el-table-column prop="name" label="保健方式" width="180">
            <template v-slot="scoped">
                <template v-if="scoped.row.isEditing">
                    <el-input style="width: 120px;" v-model="scoped.row.informatName" />
                </template>
                <template v-else>
                    {{ scoped.row.informatName }}
                </template>
            </template>
        </el-table-column>
        <el-table-column prop="address" label="保健方法" width="180">
            <template v-slot="scoped">
                <template v-if="scoped.row.isEditing">
                    <el-input style="width: 120px;" v-model="scoped.row.health" />
                </template>
                <template v-else>
                    {{ scoped.row.health }}
                </template>
            </template>
        </el-table-column>
        <el-table-column label="操作" width="240">
            <template v-slot="scoped">
                <template v-if="scoped.row.isEditing">
                    <el-button link @click="saveRow(scoped.row, scoped.$index)">
                        <span style="color:black;">{{ scoped.row.informatId && scoped.row.informatId !== 0 ? '修改' : '保存'
                        }}</span>
                    </el-button>
                    <el-button link @click="cancelEdit(scoped.row, scoped.$index)">
                        <span style="color:black;">取消</span>
                    </el-button>
                </template>
                <template v-else>
                    <el-button link @click="editRow(scoped.row)">
                        <span style="color:black;">修改</span>
                    </el-button>
                    <el-button link @click="deleteRow(scoped.$index, scoped.row)">
                        <span style="color:black;">删除</span>
                    </el-button>
                </template>
            </template>
        </el-table-column>
    </el-table>
    <h3 style="margin-top: 20px;">动检证</h3>
    <hr>
    <el-upload v-model:file-list="fileList" action="http://localhost:27167/api/Shops/ProduQueryImg"
        list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove"
        @change="handleChange">
        <el-icon>
            <Plus />
        </el-icon>
    </el-upload>

    <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
    <h3 style="margin-top: 30px;">企业信息 <el-button @click="CuitvaCreates">设置</el-button></h3>
    <hr>
    <el-dialog v-model="dialogFormVisibles" title="新增企业信息" width="500">
        <el-form style="max-width: 600px" :model="form" label-width="auto">
            <el-form-item label="养殖场" prop="enterName">
                <el-input v-model="form.enterName" />
            </el-form-item>
            <el-form-item label="负责人" prop="sourceR">
                <el-input v-model="form.sourceR" />
            </el-form-item>
            <el-form-item label="存栏数量(只)" prop="slantNum">
                <el-input v-model="form.slantNum" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForms">
                    新增
                </el-button>
                <el-button @click="resetForms(ruleFormRef)">重置</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
    <div style="margin-top: 30px;">
        <span>养殖场: {{ Bind?.enterName }}</span><span style="margin-left: 200px;">负责人:{{ Bind?.sourceR }} </span>
    </div>
    <div style="margin-top: 20px;">
        <span>存栏数量(只):{{ Bind?.slantNum }} </span>
    </div>
    <h3 style="margin-top: 20px;">企业图片</h3>
    <hr>
    <el-upload v-model:file-list="fileLists" action="http://localhost:27167/api/Shops/ProduQueryImg"
        list-type="picture-card" :on-preview="handlePictureCardPreviews" :on-remove="handleRemoves"
        @change="handleChanges">
        <el-icon>
            <Plus />
        </el-icon>
    </el-upload>
</template>

<script setup lang="ts">
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { ref, reactive, onMounted } from 'vue'
import { Traceab } from '@/Http/http'
import { useRoute } from 'vue-router'
import type { UploadProps, UploadUserFile } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
const router = useRoute();

const model = ref({
    tableData: <any>[{}],
    show: false,
    setshow: false,
    setshows: false
})


const dialogFormVisible = ref(false)

const CuitvaCreate = () => {
    dialogFormVisible.value = true
}




const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<any>({
    "cuitvaId": 0,
    "sourceName": "",
    "source": "",
    "sourceDay": "",
    "sourceBrand": "",
    "sourceUser": "",
    "slantTime": "2025-08-21T11:14:13.527Z",
    "productuins": ""
})

const locationOptions = ['Home', 'Company', 'School']

const rules = reactive<FormRules>({
    sourceName: [
        { required: true, message: '品种不能为空', trigger: 'blur' },
    ],
    sourcsourceName: [
        { required: true, message: '来源不能为空', trigger: 'blur' },
    ],
    sourceDay: [
        { required: true, message: '饲养天数不能为空', trigger: 'blur' },
    ],
    sourceBrand: [
        { required: true, message: '饲养品牌不能为空', trigger: 'blur' },
    ],
    sourceUser: [
        { required: true, message: '饲养负责人不能为空', trigger: 'blur' },
    ],
    slantTime: [
        { required: true, message: '出栏日期不能为空', trigger: 'blur' },
    ],
    source: [
        { required: true, message: '来源不能为空', trigger: 'blur' },
    ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            ruleForm.productuins = router.query.productuin
            Traceab.post("/api/Shops/CuitvaCreate", { data: ruleForm }).then(res => {
                if (res.data.code == 100) {
                    ElMessage.success("养殖信息新增成功")
                    dialogFormVisible.value = false;
                    GetCultiva()

                }
                else {
                    ElMessage.error("养殖信息新增失败")
                    dialogFormVisible.value = false;
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
}))

const data = ref<any>([])
const GetCultiva = () => {
    Traceab.get("/api/Shops/CuitvaQuery", {
        params: {
            Productuins: router.query.productuin?.toString()
        }
    }).then(res => {
        data.value = res.data.data;
    }

    )
}

const AddRow = () => {
    model.value.tableData.push({
        "informatId": 0,
        "scountNum": "",
        "informatName": "",
        "health": "",
        "productuins": router.query.productuin,
        "isDel": true,
        "isEditing": true,
        "_backup": null
    })
}

const DelQx = (index: any) => {
    console.log(index)
    model.value.tableData.splice(index, 1)
}

const ImmityCreate = () => {
    // Deprecated in favor of saveRow which handles create/update per row
}

const GetImmty = () => {
    Traceab.get("/api/Shops/ImminitQuery", {
        params: {
            Productuins: router.query.productuin
        }
    }).then(res => {
        model.value.tableData = (res.data.data || []).map((row: any) => ({
            ...row,
            isEditing: false,
            _backup: null
        }))
        if (model.value.tableData.length == 0) {
            model.value.setshow = false;
            model.value.show = false
        }
        else {

            model.value.setshow = true;
            model.value.show = true
        }
    })
}

const editRow = (row: any) => {
    row._backup = { scountNum: row.scountNum, informatName: row.informatName, health: row.health }
    row.isEditing = true
}

const cancelEdit = (row: any, index: number) => {
    if (row.informatId === 0) {
        // new unsaved row → remove
        model.value.tableData.splice(index, 1)
        return
    }
    // restore from backup
    if (row._backup) {
        row.scountNum = row._backup.scountNum
        row.informatName = row._backup.informatName
        row.health = row._backup.health
    }
    row.isEditing = false
    row._backup = null
}

const saveRow = (row: any, index: number) => {
    const payload = {
        informatId: row.informatId,
        scountNum: row.scountNum,
        informatName: row.informatName,
        health: row.health,
        productuins: router.query.productuin
    }
    if (!row.informatId || row.informatId === 0) {
        // create
        Traceab.post("/api/Shops/ImmunitCreate", { data: payload }).then(res => {
            if (res.data.code == 100) {
                ElMessage.success("新增成功")
                row.isEditing = false
                row._backup = null
                GetImmty()
            } else {
                ElMessage.error("新增失败")
            }
        })
    } else {
        // update
        Traceab.put("/api/Shops/ImminitUpdate", payload).then(res => {
            if (res.data.code == 100) {
                ElMessage.success("修改成功")
                row.isEditing = false
                row._backup = null
                GetImmty()
            } else {
                ElMessage.error("修改失败")
            }
        })
    }
}

const deleteRow = (index: number, row: any) => {
    if (!row.informatId || row.informatId === 0) {
        model.value.tableData.splice(index, 1)
        return
    }
    Traceab.delete("/api/Shops/ImminitDelete", { params: { Id: row.informatId } }).then(res => {
        if (res.data.code == 100) {
            ElMessage.success("删除成功")
            model.value.tableData.splice(index, 1)
            GetImmty()
        } else {
            ElMessage.error("删除失败")
        }
    })
}

const fileList = ref<UploadUserFile[]>([

])
const Getimg = () => {

    Traceab.get("/api/Shops/ImgQuery", {
        params: {
            name: "动检证",
            Productuins: router.query.productuin
        }
    }).then(res => {
        if (res.data.data.length > 0) {
            for (let i = 0; i <= res.data.data.length; i++) {
                fileList.value.push({
                    uid: 0,
                    name: "",
                    url: "",
                })
                i++;
            }


        }
        res.data.data.forEach((c: any, index: number) => {
            fileList.value[index].url = c.imgUrl
        });

        console.log(res.data.data)
    })
}


const fileLists = ref<UploadUserFile[]>([

])
const Getimgs = () => {
    Traceab.get("/api/Shops/ImgQuery", {
        params: {
            name: "企业图片",
            Productuins: router.query.productuin
        }
    }).then(res => {
        if (res.data.data.length > 0) {
            for (let i = 0; i <= res.data.data.length; i++) {
                fileLists.value.push({
                    uid: 0,
                    name: "",
                    url: "",
                })
                i++;
            }


        }
        res.data.data.forEach((c: any, index: number) => {
            fileLists.value[index].url = c.imgUrl
        });

        console.log(res.data.data)
    })
}

const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles)
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
}
const handleRemoves: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles)
}

const handlePictureCardPreviews: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
}
const ruleFormRefs = ref<FormInstance>()
const ruleForms = reactive<any>({
    "enterId": 0,
    "enterName": "",
    "sourceR": "",
    "slantNum": "",
    "productuin": ""
})

const form = ref<any>({
    "enterId": 0,
    "enterName": "",
    "sourceR": "",
    "slantNum": 0,
    "productuin": ""
})
const CuitvaCreates = () => {
    dialogFormVisibles.value = true
}
const dialogFormVisibles = ref(false)
const submitForms = () => {

    form.value.productuin = router.query.productuin
    console.log(form.value)
    Traceab.post("/api/Shops/EnterCreate", form.value).then(res => {
        if (res.data.code == 100) {
            ElMessage.success("企业信息新增成功")
            dialogFormVisibles.value = false;
            GetCultiva()

        }
        else {
            ElMessage.error("企业信息新增失败")
            dialogFormVisibles.value = false;
        }
    })

}
const Bind = ref<any>([])
const GetEnter = () => {
    Traceab.get("/api/Shops/EnterQuery", {
        params: {
            Productuin: router.query.productuin
        }
    }).then(res => {
        Bind.value = res.data.data;
    })
}



const resetForms = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}
const datapsf = ref({
    "imgId": 0,
    "name": "动检证",
    "imgUrl": "",
    "productuins": ""
})


const handleChange: UploadProps['onChange'] = (uploadFile) => {
    debugger
    let a = ""
    let con = 0;
    // 获取新添加图片的地址
    if (uploadFile.status === 'success' && uploadFile.response) {
        // 本地文件的临时地址
        const localUrl = <any>(uploadFile.response)
        console.log('本地临时地址:', localUrl)
        a = localUrl
        datapsf.value.imgUrl = a.substring(5)
        datapsf.value.productuins = router.query.productuin
        Traceab.post("/api/Shops/ImgInforCreate", {
            data: datapsf.value
        }).then(res => {
            if (res.data.code == 100) {
                ElMessage.success("上传图片成功")

            }
            else {
                ElMessage.error("上传图片失败")
            }
        })
    }
}
const datapsfs = ref({
    "imgId": 0,
    "name": "企业图片",
    "imgUrl": "",
    "productuins": ""
})


const handleChanges: UploadProps['onChange'] = (uploadFile) => {
    debugger

    let a = ""
    let con = 0;
    // 获取新添加图片的地址
    if (uploadFile.status === 'success' && uploadFile.response) {
        // 本地文件的临时地址
        const localUrl = <any>(uploadFile.response)
        console.log('本地临时地址:', localUrl)
        a = localUrl
        datapsfs.value.imgUrl = a.substring(5)
        datapsfs.value.productuins = router.query.productuin
        Traceab.post("/api/Shops/ImgInforCreate", {
            data: datapsfs.value
        }).then(res => {
            if (res.data.code == 100) {
                ElMessage.success("上传图片成功")

            }
            else {
                ElMessage.error("上传图片失败")
            }
        })
    }
}

onMounted(() => {
    GetCultiva();
    GetImmty();
    GetEnter();
    Getimg();
    Getimgs();
})

</script>